package gui_layer;

import java.util.List;
import java.util.Vector;

import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;

import model_layer.Product;
import ctr_layer.ProductCtr;

@SuppressWarnings("serial")
public abstract class AddProductGUI extends UniversalAddWindow
{
	private List<Product> all_products;
	private ProductCtr prod_ctr;
	protected String[] column_names = { "Art number", "Name", "Quantity", "Retail Price", "Profit %", "Sale Price" };
	public AddProductGUI()
	{
		prod_ctr = new ProductCtr();
		prepare_table(new Object[0][5], column_names);
		get_non_deleted_products();
		customize();
		this.setTitle("Add Products");
		this.addInternalFrameListener(new InternalFrameAdapter()
		{
			@Override
			public void internalFrameActivated(InternalFrameEvent arg0)
			{
				dynamically_search();
				
			}
		});
	}
	
	private void customize()
	{
		btnCancel.setText("Close");
		search_lbl.setText("Name/ID");
		
		table.getColumnModel().getColumn(2).setCellRenderer(new MarkingCellRenderer());
	}
	
	private void get_non_deleted_products()
	{
		all_products = prod_ctr.find_non_deleted_products();
	}

	@Override
	protected void dynamically_search()
	{
		String text = search_field.getText();
		MyTableModel mtm = (MyTableModel) table.getModel();
		Vector<Object[]> vector = new Vector<Object[]>();
		Object[] data;
		int next_row = 0;
		MarkingCellRenderer mcr = (MarkingCellRenderer) table.getColumnModel().getColumn(2).getCellRenderer();
		for(Product prod : all_products)
		{
			if(prod.getName().startsWith(text) || prod.getId().startsWith(text))
			{
				
				data = new Object[6];
				data[0] = Integer.parseInt(prod.getId());
				data[1] = prod.getName();
				float quantity = prod.getQuantity();
				data[2] = quantity;
				
				if(quantity <= 0)
				{
					mcr.add_warning_cell(next_row);
					mcr.remove_notification_cell(next_row);
				}
				else if(quantity < prod.getMin_amount())
				{
					mcr.add_notification_cell(next_row);
					mcr.remove_warning_cell(next_row);
				}
				else
				{
					mcr.remove_notification_cell(next_row);
					mcr.remove_warning_cell(next_row);
				}
				next_row++;
				float last_retail_price = prod.getLast_retail_price();
				if(last_retail_price == 0)
				{
					data[3] = null;
					data[4] = null;
				}
				else
				{
					data[3] = last_retail_price;
					data[4] = (prod.getPrice() - last_retail_price)/last_retail_price * 100;
				}
				
				data[5] = prod.getPrice();
				vector.add(data);
			}
		}
		Object[][] filling = new Object[vector.size()][6];
		for(int i = 0; i < vector.size(); i++)
		{
			filling[i] = vector.get(i);
		}
		mtm.setDataVector(filling, column_names);
		table.getColumnModel().getColumn(2).setCellRenderer(mcr);
	}

	@Override
	protected void show_non_deleted()
	{
		get_non_deleted_products();
		dynamically_search();
	}

}
